﻿using System;
using System.Web.Mvc;
using System.Web.Security;
using log4net;

namespace EnetaMvc.Web.Attributes
{
    public class EnetaAuthorizeAttribute : AuthorizeAttribute
    {
        private readonly ILog _logger;

        public EnetaAuthorizeAttribute()
        {
            _logger = LogManager.GetLogger(typeof(MvcApplication));
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAuthenticated)
            {
                _logger.Debug("Request is forbidden for user " + filterContext.HttpContext.User.Identity.Name);
                _logger.Debug("Required roles " + Roles);

                filterContext.Result = new HttpStatusCodeResult(403);
            }
            else
            {
                base.HandleUnauthorizedRequest(filterContext);
            }
        }
    }
}